package com.cjs.hegui30;

import android.app.AndroidAppHelper;
import android.content.Context;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import com.cjs.hegui30.config.PrivacyApiManager;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class HookTrack implements IXposedHookLoadPackage {
    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
        XposedBridge.log("[Privacy] 开始监控应用: " + lpparam.packageName);

        // 在Application onCreate之前进行Hook配置
        Class<?> applicationClass = XposedHelpers.findClass("android.app.Application", lpparam.classLoader);
        XposedHelpers.findAndHookMethod(applicationClass, "onCreate", new de.robv.android.xposed.XC_MethodHook() {
            @Override
            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                final Context context = AndroidAppHelper.currentApplication().getApplicationContext();
                if (context != null) {
                    // 创建CountDownLatch等待配置加载
                    final CountDownLatch loadLatch = new CountDownLatch(1);

                    // 在新线程中加载配置
                    new Thread(() -> {
                        try {
                            // 同步等待配置加载完成
                            PrivacyApiManager.getInstance().loadConfigSync(context, loadLatch);
                        } catch (Exception e) {
                            XposedBridge.log("[Privacy] 配置加载异常: " + e.getMessage());
                            loadLatch.countDown();
                        }
                    }).start();

                    // 等待配置加载完成
                    try {
                        if (!loadLatch.await(10, TimeUnit.SECONDS)) {
                            XposedBridge.log("[Privacy] 配置加载超时，使用默认配置");
                        }
                    } catch (InterruptedException e) {
                        XposedBridge.log("[Privacy] 配置加载等待被中断");
                    }

                    // 配置加载完成后进行Hook
                    DumpMethodHook.handleLoadPackage(lpparam);
                    XposedBridge.log("[Privacy] Hook配置加载完成，允许应用继续执行");
                }
            }
        });

        // Hook isModuleActive方法用于状态检测
        if (lpparam.packageName.equals("com.cjs.hegui30")) {
            Class<?> mainActivityClass = XposedHelpers.findClass("com.cjs.hegui30.MainActivity", lpparam.classLoader);
            XposedHelpers.findAndHookMethod(mainActivityClass, "isModuleActive",
                    de.robv.android.xposed.XC_MethodReplacement.returnConstant(true));
            XposedBridge.log("[Privacy] Hook模块状态检测");
        }
    }
}
